package com.moli.lumpSugar.common.exception;


import com.moli.lumpSugar.common.domain.vo.response.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @program: LumpSugarChat
 * @description: 全局异常捕获
 * @author: zhangjt
 * @create: 2024-10-24 15:51
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ApiResult<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder errMsg = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(fieldError -> {
            errMsg.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(";");
        });
        return ApiResult.fail(CommonErrorEnum.PARAM_VALID.getErrorCode(),errMsg.toString());
    }

    /*
    * 业务异常全局捕获
    * */
    @ExceptionHandler(value = BusinessException.class)
    public ApiResult<?> handleThrowable(BusinessException e) {
        log.error("BusinessException Error! This is reason -> {}", e);
        return ApiResult.fail(e.getErrorCode(),e.getErrorMsg());
    }

    /*
     * 最后兜底未知的异常
     * */
    @ExceptionHandler(value = Throwable.class)
    public ApiResult<?> handleThrowable(Throwable e) {
        log.error("System Error! This is reason -> {}", e);
        return ApiResult.fail(CommonErrorEnum.SYSTEM_ERROR.getErrorCode(),CommonErrorEnum.SYSTEM_ERROR.getErrorMsg());
    }
}
